﻿#-------------------------------------------------------------------------------
# Name:        memorymap
# Purpose:
#
# Author:      SUPER_紫电  QQ:911344755
#
# Created:     08/01/2023
# Copyright:   (c) SUPER_紫电 2022 All rights reserved.
# Licence:     <Modified BSD License>
#-------------------------------------------------------------------------------

import os
from multiprocessing.shared_memory import SharedMemory

BUF_SIZE = 0x2000000

mmap_name = 'trex_shared_memory_' + str(os.getpid())

def create_shared_memory():
    global shm
    global filemap
    try:
        shm = SharedMemory(mmap_name, True, BUF_SIZE)
        filemap = SharedMemory(mmap_name, False, BUF_SIZE)
        return True
    except:
        return False

def close_shared_memory():
    global shm
    global filemap
    if filemap != None:
        filemap.close()
    if shm != None:
        shm.close()

def read_shared_memory(buffer, offset, size):
    global filemap
    try:
        buffer[offset:offset+size] = filemap.buf[offset:offset+size]
        return True
    except:
        return False

def write_shared_memory(buffer, offset, size):
    global filemap
    try:
        filemap.buf[offset:offset+size] = buffer[offset:offset+size]
        return True
    except:
        return False
